package com.example.edu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.edu.client.MemberClient;
import com.example.edu.entity.Comment;
import com.example.edu.service.CommentService;
import com.example.user.entity.UcenterMember;
import com.example.user.utils.JwtUtils;
import com.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-07-20
 */
@RestController
@RequestMapping("/edu")
public class CommentController {
    @Autowired
    CommentService commentService;
    
    @Autowired
    MemberClient memberClient;

    @PostMapping("/comment")
    public Result saveComment(@RequestBody Comment comment, HttpServletRequest request){

        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)){
            return Result.error().code(20001).message("请登录");
        }
        UcenterMember member = memberClient.getMemberById(memberId);
        comment.setMemberId(memberId);
        comment.setNickname(member.getNickname());
        comment.setAvatar(member.getAvatar());

        commentService.save(comment);

        return Result.ok();
    }
    
    @GetMapping("/comment/{current}/{limit}/{courseId}")
    public Result getComment(@PathVariable Long current,@PathVariable Long limit,@PathVariable String courseId){
    	System.out.println("jinrucomment");

        Page<Comment> commentPage = new Page<>(current,limit);
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        queryWrapper.orderByDesc("gmt_create");
        commentService.page(commentPage, queryWrapper);
        List<Comment> commentList = commentPage.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("items", commentList);
        map.put("current", commentPage.getCurrent());
        map.put("pages", commentPage.getPages());
        map.put("size", commentPage.getSize());
        map.put("total", commentPage.getTotal());
        map.put("hasNext", commentPage.hasNext());
        map.put("hasPrevious", commentPage.hasPrevious());
        System.out.println(map);
      
        return Result.ok().data(map);
    }

}

